﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;
using TrainingManagerSystem.WebUI.Models;
using TrainingManagerSystem.WebUI.TrainingManagerSystemService;

namespace TrainingManagerSystem.WebUI.Models
{
    #region Create TreeView
    public interface IComposite<T>
    {

        T Parent { get; }

        ISet<T> Children { get; }

    }

    public class CompositeThing : IComposite<CompositeThing>
    {
        public CompositeThing()
        {

            Children = new HashSet<CompositeThing>();

        }

        public string Name { get; set; }
        public CompositeThing Parent { get; set; }
        public ISet<CompositeThing> Children { get; set; }
        public int Id { get; set; }

    }

    public static class TreeRenderHtmlHelper
    {
        public static MvcHtmlString RenderTree<T>(

            this HtmlHelper htmlHelper,

            IEnumerable<T> rootLocations,

            Func<T, string> locationRenderer)

            where T : IComposite<T>
        {
            return new TreeRenderer<T>(rootLocations, locationRenderer).Render();
        }

    }

    public class TreeRenderer<T> where T : IComposite<T>
    {

        private readonly Func<T, string> _locationRenderer;

        private readonly IEnumerable<T> _rootLocations;

        private HtmlTextWriter _writer;

        /// <summary>
        /// Create Extension for TreeView
        /// </summary>
        /// <param name="rootLocations"></param>
        /// <param name="locationRenderer"></param>
        public TreeRenderer(

            IEnumerable<T> rootLocations,

            Func<T, string> locationRenderer)
        {

            _rootLocations = rootLocations;

            _locationRenderer = locationRenderer;

        }

        /// <summary>
        /// Render Tree to MVCString
        /// </summary>
        /// <returns></returns>
        public MvcHtmlString Render()
        {

            _writer = new HtmlTextWriter(new StringWriter());

            RenderLocations(_rootLocations);

            return new MvcHtmlString(_writer.InnerWriter.ToString());

        }

        /// <summary>
        /// Recursively walks the location tree outputting it as hierarchical UL/LI elements
        /// </summary>
        /// <param name="locations"></param>
        private void RenderLocations(IEnumerable<T> locations)
        {

            if (locations == null) return;

            var enumerable = locations as List<T> ?? locations.ToList();
            var count = enumerable.Count();
            if (count == 0) return;

            InUl(() => enumerable.ForEach(location => InLi(() =>
            {

                _writer.Write(_locationRenderer(location));

                RenderLocations(location.Children);

            })));

        }

        /// <summary>
        /// Write UL tag
        /// </summary>
        /// <param name="action"></param>
        private void InUl(Action action)
        {
            _writer.AddAttribute("class", "hidden");
            _writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            action();
            _writer.RenderEndTag();
            _writer.WriteLine();
        }

        /// <summary>
        /// Write Li tag
        /// </summary>
        /// <param name="action"></param>
        private void InLi(Action action)
        {

            _writer.RenderBeginTag(HtmlTextWriterTag.Li);
            _writer.AddAttribute("href", "javascript:;");
            _writer.AddAttribute("onclick", "getTreeViewDataClick(this)");
            _writer.RenderBeginTag(HtmlTextWriterTag.A);
            action();
            _writer.RenderEndTag();
            _writer.WriteLine();
            _writer.RenderEndTag();
            _writer.WriteLine();
        }
    }
}
    #endregion
#region Account-Course
public static class AcountCourse
{

    public static MvcHtmlString RenderTableConfigurationPopup(this HtmlHelper htmlHelper)
    {
        return new MvcHtmlString("<div class='acTitle title-view'>Selected Fields</div><table id='selectedFileds'><tr><td><input type='checkbox' id='selectAll'/> Select all</td></tr><tr><td><input type='checkbox' checked='checked' class='fields'/> Employee Id</td><td><input type='checkbox' checked='checked' class='fields'/> Account Name</td><td><input type='checkbox' checked='checked' class='fields'/> FullName</td><td><input type='checkbox' checked='checked' class='fields'/> Job Title</td></tr><tr><td><input type='checkbox' checked='checked' class='fields'/> Department</td><td><input type='checkbox' checked='checked' class='fields'/> Course Name</td><td><input type='checkbox' checked='checked' class='fields'/> Course Cost</td><td><input type='checkbox' class='fields'/> Currency</td></tr><tr><td><input type='checkbox' class='fields'/> Location</td><td><input type='checkbox' class='fields'/> Start Date</td><td><input type='checkbox' class='fields'/> End Date</td><td><input type='checkbox' class='fields'/> Pass covarage</td></tr><tr><td><input type='checkbox' class='fields'/> Time Commit</td><td><input type='checkbox' class='fields'/> Course Year</td><td><input type='checkbox' class='fields'/> Duration</td><td><input type='checkbox' class='fields'/> Final Result</td><td><input type='checkbox' class='fields'/> Notes</td></tr></table><div class='btns'><input type='button' value='Cancel' id='cancelBtn'/><input type='button' value='Accept' id='changeFields'/></div>");
    }

    public static MvcHtmlString RenderSearchOption(this HtmlHelper htmlHelper)
    {
        return new MvcHtmlString("<form action='/' method='post'><div class='div-search'><table><tr><td>Account Name</td><td><input id='accName' class='txt' type='text'/></td><td>Employee Id</td><td><input id='employeeID' class='txt' type='text'/></td></tr><tr><td>Course Category</td><td><select id='category'><option>All</option><option>Fresher</option><option>FWA</option></select></td><td>Course Name</td><td><input id='courseName' class='txt' type='text'/></td></tr><tr><td>Course Year</td><td><input id='courseYear' class='txt_year' id='txt_year' type='text'/></td><td>Experience</td><td><input id='startDate' class='experienceStart' type='text'/>>><input id='endDate' class='experienceEnd' type='text'/>(Months)</td></tr><tr><td><span id='advanceBtn'>Advance Options</span></td><td></td></tr><tr class='advance'><td>Full Name</td><td><input id='fullName' class='txt' type='text'/></td><td>Role</td><td><select id='role'><option>All</option><option>Manager</option></select></td></tr><tr class='advance'><td>Course End Date</td><td><input id='courseStart' class='courseStart' type='text'/>>><input id='CourseEnd' class='courseStart' type='text'/></td><td>Account Status</td><td><select id='accountStatus'><option>All</option><option>Avaiable</option><option>Not Avaiable</option></select></td></tr><tr class='advance'><td>Acount Location</td><td><select id='accountLocation'><option>HN</option><option>HCM</option><option>DN</option></select></td><td>Contract Type</td><td><select id='accountContract'><option>All</option><option>Hợp đồng ngắn hạn</option><option>Hợp đồng thời vụ</option></select></td></tr></table><div id='advanceOptions'><table></table></div></div><div class='float-right'><button type='button' id='searchAccountCourse' class='btn'><span class='i-invertedSearchLoupe'>SEARCH</span></button></div></form>");
    }

    public static MvcHtmlString RenderColumns(this HtmlHelper htmlHelper)
    {
        return new MvcHtmlString("<thead><tr><th>Employee ID</th><th>Account</th><th>Full Name</th><th>Job Title</th><th>Department</th><th>Course</th><th>Course Cost</th><th>Currency</th><th>Location</th><th>Start Date</th><th>End Date</th><th>Pass coverage</th><th>Time Commit</th><th>Course Year</th><th>Duration</th><th>Final Result</th><th>Notes</th><th style='display: none;'>Totals</th></tr></thead>");
    }

    public static MvcHtmlString RenderDetailAccountCourse(this HtmlHelper htmlHelper)
    {
        return new MvcHtmlString(" <div class='acTitle title-view'>Details Account Course</div><div class='div-search'><table style='margin: 25px;'><tr><td class='label bold'>Employee ID: </td><td id='employeeId'>00001002</td><td class='label bold'>Rank Name: </td><td id='rankName'>Loading...</td></tr><tr><td class='label bold'>Full Name: </td><td id='fullName'>Nguyễn Trung Hiếu</td><td class='label bold'>Department: </td><td id='department'>FSO HN >> HN BOD</td></tr><tr><td class='label bold'>Account Name: </td><td id='account'>HieuNT28</td><td class='label bold'>Location: </td><td id='location'>Hà Nội</td></tr><tr><td class='label bold'>Job Title: </td><td id='job'>Project Manager</td><td class='label bold'>Contract Type: </td><td id='contract'>HĐ không xác định thời hạn</td></tr></table></div><span class='btns'><input type='button' value='Close' id='btnCloseI'/></span>");
    }

    public static IEnumerable<CompositeThing> Childs(int id, List<Department> list, ref int i)
    {
        var result = new List<CompositeThing>();
        foreach (var department in list.Where(department => department.ParentDepartmentId == id))
        {
            var obj = new CompositeThing
                          {
                              Name = department.DepartmentName + '_' + department.DepartmentId,
                              Children = new HashSet<CompositeThing>(Childs(department.DepartmentId, list, ref i)),
                              Id = department.DepartmentId
                          };

            result.Add(obj);
            foreach (var c in obj.Children)
            {
                c.Parent = obj;
            }
            i++;
        }
        return result;
    }

    public static List<CompositeThing> GetDataForTreeView(List<Department> list)
    {
        var result = new List<CompositeThing>();
        var n = list.Count;
        var i = 0;
        while (i < n)
        {
            var obj = new CompositeThing
            {
                Id = list[i].DepartmentId,
                Name = list[i].DepartmentName + '_' + list[i].DepartmentId,
                Children = new HashSet<CompositeThing>(Childs(list[i].DepartmentId, list, ref i))

            };
            result.Add(obj);
            foreach (var tt in obj.Children)
            {
                tt.Parent = obj;
            }
            i++;
        }
        return result;
    }
#endregion
}
